package cn.estore.dao;


/* @Author: 顾建宇
 * @Date: 2024/12/16 22:30
 * course
 */

import cn.estore.entity.Order;
import cn.estore.util.DBConnection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.estore.entity.Order;
import cn.estore.util.DBConnection;

public class OrderDao {

    private DBConnection jdbc;

    public OrderDao() {
        jdbc = new DBConnection();
    }

    // 私有方法，用于从结果集填充Order对象并添加到列表中
    private void fillOrderListFromResultSet(ResultSet rs, List<Order> list) throws SQLException {
        while (rs.next()) {
            Order order = new Order();
            order.setId(rs.getInt("id"));
            order.setUserId(rs.getInt("user_id"));
            order.setProductId(rs.getInt("product_id"));
            order.setOrderNumber(rs.getString("order_number"));
            order.setCreateTime(rs.getTimestamp("create_time"));
            order.setProductQuantity(rs.getInt("product_quantity"));
            order.setActualPrice(rs.getDouble("actual_price"));
            order.setTotalAmount(rs.getDouble("total_amount"));
            list.add(order);
        }
    }

    // 查询所有订单记录的方法
    public List<Order> selectAllOrders() {
        List<Order> list = new ArrayList<>();
        Connection conn = jdbc.getConnection();
        try (PreparedStatement stmt = conn.prepareStatement("select * from `order`");
             ResultSet rs = stmt.executeQuery()) {
            fillOrderListFromResultSet(rs, list);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    // 根据订单ID查询一条订单记录的方法
    public Order selectOrderById(int orderId) {
        Order order = null;
        Connection conn = jdbc.getConnection();
        try (PreparedStatement stmt = conn.prepareStatement("select * from `order` where id =?")) {
            stmt.setInt(1, orderId);
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    order = new Order();
                    List<Order> orderList = new ArrayList<>(); // 创建一个临时列表来存放解析出的Order对象
                    fillOrderListFromResultSet(rs, orderList); // 将结果集数据填充到临时列表中
                    if (!orderList.isEmpty()) {
                        order = orderList.get(0); // 由于是根据id查询单个订单，取列表中的第一个（也是唯一的）元素赋值给order
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return order;
    }

    // 根据用户ID查询该用户的所有订单记录的方法
    public List<Order> selectOrdersByUserId(int userId) {
        List<Order> list = new ArrayList<>();
        Connection conn = jdbc.getConnection();
        try (PreparedStatement stmt = conn.prepareStatement("select * from `order` where user_id =?")) {
            stmt.setInt(1, userId);
            try (ResultSet rs = stmt.executeQuery()) {
                fillOrderListFromResultSet(rs, list);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    // 根据商品ID查询包含该商品的所有订单记录的方法
    public List<Order> selectOrdersByProductId(int productId) {
        List<Order> list = new ArrayList<>();
        Connection conn = jdbc.getConnection();
        try (PreparedStatement stmt = conn.prepareStatement("select * from `order` where product_id =?")) {
            stmt.setInt(1, productId);
            try (ResultSet rs = stmt.executeQuery()) {
                fillOrderListFromResultSet(rs, list);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    // 插入一条订单记录到order表的方法
    public boolean insertOrder(Order order) {
        Connection conn = jdbc.getConnection();
        String sql = "insert into `order` (user_id, product_id, order_number,product_quantity, actual_price, total_amount) " +
                "values (?,?,?,?,?,?)";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, order.getUserId());
            stmt.setInt(2, order.getProductId());
            stmt.setString(3, order.getOrderNumber());
            stmt.setInt(4, order.getProductQuantity());
            stmt.setDouble(5, order.getActualPrice());
            stmt.setDouble(6, order.getTotalAmount());

            stmt.executeUpdate();
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 更新订单记录的方法
    public boolean updateOrder(Order order) {
        Connection conn = jdbc.getConnection();
        String sql = "update `order` set user_id =?, product_id =?, order_number =?, product_quantity =?, actual_price =?, total_amount =? where id =?";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, order.getUserId());
            stmt.setInt(2, order.getProductId());
            stmt.setString(3, order.getOrderNumber());
            stmt.setInt(4, order.getProductQuantity());
            stmt.setDouble(5, order.getActualPrice());
            stmt.setDouble(6, order.getTotalAmount());

            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 根据订单ID删除订单记录的方法
    public boolean deleteOrderById(int orderId) {
        Connection conn = jdbc.getConnection();
        try (PreparedStatement stmt = conn.prepareStatement("delete from `order` where id =?")) {
            stmt.setInt(1, orderId);

            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
}
